import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  // 重置状态
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login 登录
  login({ commit }, userInfo) {
    console.log(userInfo)
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
       const token=response.data  
        // 令牌提交vuex管理
        commit('SET_TOKEN', token)
        // 把令牌写入到浏览器 cookie中
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info 取得不前登录用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 读取后台当前用户信息
      getInfo().then(response => {
        const { data } = response

        if (!data) {
          return reject('令牌无效，请重新登录.')
        }

        // 后台 只取 name 和 头像
        const { nickName } = data
        //const nickName =data.nickName
        const avatar='https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'

        commit('SET_NAME', nickName)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout 注销/退出 vuex  commit, state
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 调用java后台注销
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        // 重置路由
        resetRouter()
        // 调用重置状态
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token 移出token方法
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      //es6 Promise异步编程模式通过
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
